<template>
  <view class="statistics-container">
    <!-- 时间筛选器 -->
    <view class="time-filter">
      <view class="time-selector">
        <button 
          v-for="time in timeFilters" 
          :key="time.value"
          class="time-btn"
          :class="{ active: currentTimeFilter === time.value }"
          @click="changeTimeFilter(time.value)"
        >
          {{ time.label }}
        </button>
      </view>
      <view class="custom-time">
        <text>自定义</text>
      </view>
    </view>

    <!-- 收支概览 -->
    <view class="statistics-card">
      <view class="card-title">
        <text>收支概览</text>
        <text>{{ currentTimeLabel }}</text>
      </view>
      <view class="overview">
        <view class="overview-item">
          <text>收入</text>
          <view class="overview-value income-value">¥{{ formatAmount(overview.income) }}</view>
        </view>
        <view class="overview-item">
          <text>支出</text>
          <view class="overview-value expense-value">¥{{ formatAmount(overview.expense) }}</view>
        </view>
        <view class="overview-item">
          <text>结余</text>
          <view class="overview-value balance-value">¥{{ formatAmount(overview.balance) }}</view>
        </view>
      </view>
    </view>

    <!-- 支出分类分布 -->
    <view class="statistics-card">
      <view class="card-title">
        <text>支出分类分布</text>
      </view>
      <view v-if="loading" class="loading">加载中...</view>
      <view v-else>
        <view class="chart-container">
          <canvas id="categoryChart" canvas-id="categoryChart" class="chart-canvas"></canvas>
        </view>
        <view class="category-list">
          <view 
            v-for="category in categoryExpenses" 
            :key="category.id"
            class="category-item"
          >
            <view class="category-info">
              <view class="category-color" :style="{ backgroundColor: category.color }"></view>
              <text class="category-name">{{ category.name }}</text>
            </view>
            <view>
              <text class="category-amount">¥{{ formatAmount(category.amount) }}</text>
              <text class="category-percent">{{ category.percent }}%</text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 收支趋势 -->
    <view class="statistics-card">
      <view class="card-title">
        <text>收支趋势</text>
      </view>
      <view class="chart-container">
        <canvas id="trendChart" canvas-id="trendChart" class="chart-canvas"></canvas>
      </view>
    </view>

    <!-- 导出按钮 -->
    <button class="export-btn" @click="exportData">导出数据</button>
  </view>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue';
import { onReady } from '@dcloudio/uni-app';

// 时间筛选器
const timeFilters = ref([
  { label: '本周', value: 'week' },
  { label: '本月', value: 'month' },
  { label: '本季度', value: 'quarter' },
  { label: '本年', value: 'year' }
]);

const currentTimeFilter = ref('week');
const currentTimeLabel = computed(() => {
  const filter = timeFilters.value.find(f => f.value === currentTimeFilter.value);
  return filter ? filter.label : '本周';
});

// 收支概览数据
const overview = reactive({
  income: 12580.50,
  expense: 8432.75,
  balance: computed(() => overview.income - overview.expense)
});

// 分类支出数据
const categoryExpenses = ref([
  { id: 1, name: '餐饮美食', amount: 2450.30, color: '#FF6B6B', percent: 29 },
  { id: 2, name: '交通出行', amount: 980.50, color: '#4ECDC4', percent: 12 },
  { id: 3, name: '购物消费', amount: 3200.75, color: '#FFD166', percent: 38 },
  { id: 4, name: '住房物业', amount: 1801.20, color: '#06D6A0', percent: 21 }
]);

// 加载状态
const loading = ref(false);

// 模拟分类API
const categoryApi = {
  getCategoryList: async () => {
    // 模拟网络请求
    await new Promise(resolve => setTimeout(resolve, 500));
    return {
      data: [
        { id: 1, name: '餐饮美食', color: '#FF6B6B' },
        { id: 2, name: '交通出行', color: '#4ECDC4' },
        { id: 3, name: '购物消费', color: '#FFD166' },
        { id: 4, name: '住房物业', color: '#06D6A0' }
      ]
    };
  }
};

// 方法
const changeTimeFilter = async (filter) => {
  currentTimeFilter.value = filter;
  await loadStatisticsData();
};

const formatAmount = (amount) => {
  return amount.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
};

// 加载分类数据
const loadCategories = async () => {
  try {
    loading.value = true;
    const response = await categoryApi.getCategoryList();
    // 这里可以处理分类数据
    console.log('分类数据加载成功:', response.data);
  } catch (error) {
    console.error('加载分类数据失败:', error);
    uni.showToast({
      title: '加载分类数据失败',
      icon: 'none'
    });
  } finally {
    loading.value = false;
  }
};

// 加载统计数据
const loadStatisticsData = async () => {
  try {
    loading.value = true;
    // 模拟数据加载
    await new Promise(resolve => setTimeout(resolve, 300));
    console.log(`加载${currentTimeLabel.value}统计数据`);
    
    // 在实际应用中，这里应该调用API获取统计数据
  } catch (error) {
    console.error('加载统计数据失败:', error);
    uni.showToast({
      title: '加载统计数据失败',
      icon: 'none'
    });
  } finally {
    loading.value = false;
  }
};

const exportData = () => {
  uni.showModal({
    title: '导出数据',
    content: '确定要导出当前统计周期的数据吗？',
    success: (res) => {
      if (res.confirm) {
        uni.showToast({
          title: '数据导出成功',
          icon: 'success'
        });
      }
    }
  });
};

// 生命周期
onMounted(async () => {
  await loadCategories();
  await loadStatisticsData();
});

// 监听时间筛选器变化
watch(currentTimeFilter, async () => {
  await loadStatisticsData();
});

// uniapp页面就绪后初始化图表
onReady(() => {
  // 这里可以初始化uniapp的图表组件
  console.log('页面准备就绪，可以初始化图表');
});
</script>

<style scoped>
.statistics-container {
  padding: 20rpx;
  min-height: 100vh;
  background-color: #f5f5f5;
}

/* 时间筛选器 */
.time-filter {
  background-color: #fff;
  border-radius: 10rpx;
  margin-bottom: 20rpx;
  padding: 20rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.time-selector {
  display: flex;
  align-items: center;
  gap: 20rpx;
  flex-wrap: wrap;
}

.time-btn {
  padding: 10rpx 20rpx;
  border-radius: 8rpx;
  background-color: #f0f0f0;
  font-size: 28rpx;
  border: none;
}

.time-btn.active {
  background-color: #007AFF;
  color: white;
}

/* 统计卡片 */
.statistics-card {
  background-color: #fff;
  border-radius: 10rpx;
  margin-bottom: 20rpx;
  padding: 20rpx;
}

.card-title {
  font-size: 32rpx;
  font-weight: 600;
  margin-bottom: 20rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

/* 收支概览 */
.overview {
  display: flex;
  justify-content: space-between;
  text-align: center;
}

.overview-item {
  flex: 1;
  padding: 20rpx;
}

.overview-value {
  font-size: 36rpx;
  font-weight: bold;
  margin: 10rpx 0;
}

.income-value {
  color: #10B981;
}

.expense-value {
  color: #EF4444;
}

.balance-value {
  color: #007AFF;
}

/* 图表容器 */
.chart-container {
  width: 100%;
  height: 400rpx;
  margin-top: 20rpx;
}

.chart-canvas {
  width: 100%;
  height: 100%;
}

/* 分类支出列表 */
.category-list {
  margin-top: 20rpx;
}

.category-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
}

.category-info {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.category-color {
  width: 20rpx;
  height: 20rpx;
  border-radius: 50%;
}

.category-name {
  font-size: 28rpx;
}

.category-amount {
  font-size: 28rpx;
  font-weight: 500;
}

.category-percent {
  font-size: 24rpx;
  color: #999;
  margin-left: 10rpx;
}

/* 加载状态 */
.loading {
  text-align: center;
  padding: 40rpx;
  color: #999;
}

/* 导出按钮 */
.export-btn {
  background-color: #007AFF;
  color: white;
  border: none;
  border-radius: 50rpx;
  padding: 20rpx 0;
  font-size: 32rpx;
  width: 100%;
  margin-top: 20rpx;
}
</style>